package com.yinda.dt.produce.module.message;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xcgame.srv.SuperRecyclerView;
import com.yinda.dt.produce.R;
import com.yinda.dt.produce.app.DemoActivity;
import com.yinda.dt.produce.app.DemoConfig;
import com.yinda.dt.produce.app.MyResponseCallback;
import com.yinda.dt.produce.module.login.LoginActivity;
import com.yinda.dt.produce.module.main.MainActivity;
import com.yinda.dt.produce.module.order.OrderDetailActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MessageActivity extends DemoActivity implements View.OnClickListener, SuperRecyclerView.OnPullRefreshListener, SuperRecyclerView.OnLoadMoreListener {

    private SuperRecyclerView srv_content;
    private int page = 0;
    private int state = 1; // 0 ：没有  1：刷新  2：加载更多

    private List<JSONObject> messages;
    private MessageAdapter adapter;

    private LinearLayout ll_left;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        ll_left = (LinearLayout) findViewById(R.id.ll_left);
        ll_left.setOnClickListener(this);

        messages = new ArrayList<>();

        srv_content = (SuperRecyclerView) findViewById(R.id.srv_content);
        srv_content.setRefreshProgressColorsRes(R.color.colorPrimary);
        srv_content.setPullRefreshEnabled(true);
        srv_content.setOnPullRefreshListener(this);
        srv_content.setLoadMoreEnabled(true);
        srv_content.setOnLoadMoreListener(this);
        srv_content.setEmptyView(R.layout.view_no_date);
        adapter = new MessageAdapter();
        srv_content.setAdapter(adapter);

        srv_content.setRefreshing();
        getMyMessageList();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_left) {
            finish();
        }
    }


    @Override
    public void onPullRefresh() {
        state = 1;
        page = 0;
        getMyMessageList();
    }

    @Override
    public void onLoadMore() {
        state = 2;
        page++;
        getMyMessageList();
    }

    private void getMyMessageList() {
        try {
            String url = getString(R.string.defaultURL) + "/phone1_0!getMyMessageList.action";
            JSONObject jsonParams = new JSONObject();
            jsonParams.put("status", 1);
            jsonParams.put("page", page);
            jsonParams.put("pageNum", 20);
            post(url, jsonParams, new MyResponseCallback() {

                @Override
                public void isNotOpenNetwork() {
                    super.isNotOpenNetwork();
                    if (state == 1) {
                        srv_content.refreshComplete();
                    }
                    if (state == 2) {
                        srv_content.loadMoreComplete(true);
                    }
                    state = 0;
                }

                @Override
                public void onCancel() {
                    super.onCancel();
                    if (state == 1) {
                        srv_content.refreshComplete();
                    }
                    if (state == 2) {
                        srv_content.loadMoreComplete(true);
                    }
                    state = 0;
                }

                @Override
                public void onFailure(int statusCode) {
                    super.onFailure(statusCode);

                    if (state == 1) {
                        srv_content.refreshComplete();
                    }
                    if (state == 2) {
                        srv_content.loadMoreComplete(true);
                    }
                    state = 0;

                }

                @Override
                public void onSuccess(JSONObject jsonResult) {
                    super.onSuccess(jsonResult);

                    try {
                        JSONObject jsonHead = jsonResult.getJSONObject("head");
                        int status = jsonHead.getInt("status");
                        String info = jsonHead.getString("info");
                        if (status == 1) {

                            JSONArray jsonMessages = jsonResult.getJSONArray("data");

                            if (state == 1) {
                                messages.clear();
                                srv_content.refreshComplete();
                            }
                            if (state == 2) {
                                if (jsonMessages.length() > 0) {
                                    srv_content.loadMoreComplete(true);
                                } else {
                                    srv_content.loadMoreComplete(false);
                                }
                            }
                            state = 0;

                            for (int i = 0; i < jsonMessages.length(); i++) {
                                JSONObject jsonOrder = jsonMessages.getJSONObject(i);
                                messages.add(jsonOrder);
                            }

                            adapter.notifyDataSetChanged();

                        } else {
                            if (info.contains("key无效") || info.toLowerCase().contains("loginout") || info.contains("未登录")) {
                                DemoConfig.getInstance(getContext()).setKey("");
                                DemoConfig.getInstance(getContext()).setIsLogin(false);
                                showToast("请重新登录");
                                Intent intent = new Intent(getContext(), LoginActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            } else {
                                showToast(info);
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void setMessageStatus(final MessageAdapter.ViewHolder holder, final JSONObject jsonMessage) {
        try {
            String url = getString(R.string.defaultURL) + "/phone1_0!setMessageCodeById.action";
            JSONObject jsonParams = new JSONObject();
            jsonParams.put("messageId", jsonMessage.getString("messageId"));
            jsonParams.put("status", "1");
            post(url, jsonParams, new MyResponseCallback(loadingDialog) {
                @Override
                public void onSuccess(JSONObject jsonResult) {
                    super.onSuccess(jsonResult);

                    try {


                        holder.iv_isRead.setVisibility(View.GONE);

                        if (jsonMessage.getInt("type") == 1) {

                            if (jsonMessage.isNull("approvalCode")) {
                                return;
                            }
                            int approvalCode = jsonMessage.getInt("approvalCode");
                            if (approvalCode >= 1 && approvalCode != 17 && approvalCode <= 18) {
                                Intent intent = new Intent(getContext(), OrderDetailActivity.class);
                                intent.putExtra("orderId", jsonMessage.getString("orderId"));
                                intent.putExtra("approvalCode", approvalCode + "");
                                intent.putExtra("orderType", jsonMessage.getString("orderType"));
                                intent.putExtra("orderStatus", "1");
                                startActivity(intent);
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {

        class ViewHolder extends RecyclerView.ViewHolder {

            LinearLayout ll_item;
            /**
             * 消息的标题
             */
            TextView tv_title;
            /**
             * 消息的内容
             */
            TextView tv_content;

            ImageView iv_isRead;

            public ViewHolder(View itemView) {
                super(itemView);

                ll_item = (LinearLayout) itemView.findViewById(R.id.ll_item);
                tv_title = (TextView) itemView.findViewById(R.id.tv_title);
                tv_content = (TextView) itemView.findViewById(R.id.tv_content);
                iv_isRead = (ImageView) itemView.findViewById(R.id.iv_isRead);

            }
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(MessageActivity.this).inflate(R.layout.adapter_message, parent, false);
            return new ViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            try {
                final JSONObject jsonMessage = messages.get(position);
                if (jsonMessage.isNull("approvalCode") || !jsonMessage.getString("messageTitle").equals("订单审批")) {
                    holder.tv_title.setText(jsonMessage.getString("messageTitle"));
                } else {
                    String approvalCode = jsonMessage.getString("approvalCode");
                    String title;
                    switch (approvalCode) {
                        case "1":
                            title = "订单申请";
                            break;
                        case "2":
                            title = "订单审批";
                            break;
                        case "3":
                            title = "计划安排";
                            break;
                        case "4":
                            title = "技术资料";
                            break;
                        case "5":
                            title = "半成品";
                            break;
                        case "6":
                            title = "黑件出厂";
                            break;
                        case "7":
                            title = "镀锌申请";
                            break;
                        case "8":
                            title = "镀锌申请-副总审批";
                            break;
                        case "9":
                            title = "白件质检";
                            break;
                        case "10":
                            title = "计划发货";
                            break;
                        case "11":
                            title = "项目收货";
                            break;
                        case "12":
                            title = "新建项目施工";
                            break;
                        case "13":
                            title = "施工质检";
                            break;
                        case "14":
                            title = "计划安排副总审核";
                            break;
                        case "15":
                            title = "改造项目施工";
                            break;
                        case "16":
                            title = "零星项目施工";
                            break;
                        default:
                            title = "订单审批";
                            break;
                    }
                    holder.tv_title.setText(title);
                }

                holder.tv_content.setText(ToDBC(jsonMessage.getString("content")));
                /**
                 * 根据消息是已读还是未读来设置该图片是否显示
                 */
                if (jsonMessage.getInt("isRead") == 0) {
                    holder.iv_isRead.setVisibility(View.VISIBLE);
                } else {
                    holder.iv_isRead.setVisibility(View.GONE);
                }

                holder.ll_item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setMessageStatus(holder, jsonMessage);
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getItemCount() {
            if (messages == null) {
                return 0;
            }
            return messages.size();
        }
    }

    /**
     * 半角转换为全角
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }
}
